package kr.hyunist.androidcomplete02saeildamil.ch33;

import java.io.IOException;
import java.util.ArrayList;

import kr.hyunist.androidcomplete02saeildamil.R;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MusicPlayerTest extends Activity {
	final String TAG = "MusicPlayerTest";
	ArrayList<MyMusic> mList;
	int mIdx = 0;
	MediaPlayer mPlayer;
	Button mPlayBtn;
	TextView mFileName;
	SeekBar mProgress;
	boolean wasPlaying;
	ListViewAdapter adapter;
	ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playaudiotest);

		mPlayer = new MediaPlayer();

		mList = new ArrayList<MyMusic>();

		mFileName = (TextView) findViewById(R.id.filename);

		adapter = new ListViewAdapter(this, mList);
		list = (ListView) findViewById(R.id.list);
		list.setAdapter(adapter);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mIdx = position;
				try {
					mPlayer.reset();
					LoadMedia(mIdx);
					mPlayer.start();

				} catch (IllegalArgumentException e) {
					return;
				} catch (SecurityException e) {
					return;
				} catch (IllegalStateException e) {
					return;
				}
			}

		});

		// sd카드가 없을시 에러처리
		/*
		 * String ext = Environment.getExternalStorageState(); String sdPath; if
		 * (ext.equals(Environment.MEDIA_MOUNTED) == false) {
		 * Toast.makeText(this, "SD카드가 반드시 필요합니다.", 1).show(); finish(); return;
		 * }
		 */

		// sd카드 루트의 mp3파일 목록을 구한다.
		/*
		 * sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
		 * File sdRoot = new File(sdPath); FilenameFilter filter = new
		 * FilenameFilter() {
		 * 
		 * @Override public boolean accept(File dir, String filename) { return
		 * filename.endsWith(".mp3"); }
		 * 
		 * };
		 */

		/*
		 * String[] mplist = sdRoot.list(filter); if (mplist.length == 0) {
		 * Toast.makeText(this, "재생할 파일이 없습니다.", 1).show(); finish(); return; }
		 * 
		 * for (String s : mplist) { mList.add(sdPath + "/" + s); }
		 */

		// mIdx = 0;

		// 버튼 클릭 리스너
		mPlayBtn = (Button) findViewById(R.id.playaudioplay);

		// 완료 리스너, 시크바 변경 리스너 등록
		mPlayer.setOnCompletionListener(mOnComplete);
		mPlayer.setOnSeekCompleteListener(mOnSeekComplete);
		mProgress = (SeekBar) findViewById(R.id.playaudioseekbar);
		mProgress.setOnSeekBarChangeListener(mOnSeek);
		mProgressHandler.sendEmptyMessageDelayed(0, 200);

		// 첫곡 읽기 및 준비
		if (LoadMedia(mIdx) == false) {
			Toast.makeText(this, "파일을 읽을 수 없습니다.", 1).show();
			finish();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mPlayer != null) {
			mPlayer.release();
			mPlayer = null;
		}
	}

	private boolean LoadMedia(int idx) {
		try {
			mPlayer.setDataSource(mList.get(idx).getData());
		} catch (IllegalArgumentException e) {
			return false;
		} catch (SecurityException e) {
			return false;
		} catch (IllegalStateException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		if (Prepare() == false) {
			return false;
		}
		mFileName.setText("파일 : " + mList.get(idx).getMusicTitle());
		mProgress.setMax(mPlayer.getDuration());
		return true;
	}

	private boolean Prepare() {
		try {
			mPlayer.prepare();
		} catch (IllegalStateException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		return true;
	}

	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.playaudioplay:
			Log.d(TAG, "이건 플레이&일시중지버튼");
			if (mPlayer.isPlaying() == false) {
				mPlayer.start();
				mPlayBtn.setText("Pause");
			} else {
				mPlayer.pause();
				mPlayBtn.setText("Play");
			}
			break;

		case R.id.playaudiostop:
			Log.d(TAG, "이건 중지버튼");

			mPlayer.stop();
			mPlayBtn.setText("Play");
			mProgress.setProgress(0);
			Prepare();

			break;

		case R.id.playaudioprev:
		case R.id.playaudionext:
			Log.d(TAG, "이건 이전 다음버튼");
			wasPlaying = mPlayer.isPlaying();

			if (v.getId() == R.id.playaudioprev) {
				mIdx = (mIdx == 0 ? mList.size() - 1 : mIdx - 1);
			} else {
				mIdx = (mIdx == mList.size() - 1 ? 0 : mIdx + 1);
			}

			mPlayer.reset();
			LoadMedia(mIdx);

			// 이전에 재생중이었으면 다음 곡 바로 재생
			if (wasPlaying) {
				mPlayer.start();
				mPlayBtn.setText("Pause");
			}
			break;
		}
	}

	// 재생 완료되면 다음곡으로
	MediaPlayer.OnCompletionListener mOnComplete = new MediaPlayer.OnCompletionListener() {

		@Override
		public void onCompletion(MediaPlayer mPlayer) {
			mIdx = (mIdx == mList.size() - 1 ? 0 : mIdx + 1);
			mPlayer.reset();
			LoadMedia(mIdx);
			mPlayer.start();
		}

	};

	// 에러 발생시 메시지 출력
	MediaPlayer.OnErrorListener mOnError = new MediaPlayer.OnErrorListener() {

		@Override
		public boolean onError(MediaPlayer mPlayer, int what, int extra) {
			String err = "OnError occured. what = " + what + ", extra = "
					+ extra;
			Toast.makeText(MusicPlayerTest.this, err, 1).show();
			return false;
		}

	};

	// 위치 이동 완료 처리
	MediaPlayer.OnSeekCompleteListener mOnSeekComplete = new MediaPlayer.OnSeekCompleteListener() {

		@Override
		public void onSeekComplete(MediaPlayer mPlayer) {
			if (mPlayer.isPlaying()) {
				mPlayer.start();
			}
		}

	};

	// 0.2초에 한번꼴로 재생 위치 갱신
	Handler mProgressHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (mPlayer == null) {
				return;
			}

			if (mPlayer.isPlaying()) {
				mProgress.setProgress(mPlayer.getCurrentPosition());
			}

			mProgressHandler.sendEmptyMessageDelayed(0, 200);
		}

	};

	// 재생위치 이동
	SeekBar.OnSeekBarChangeListener mOnSeek = new SeekBar.OnSeekBarChangeListener() {

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {

		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			if (wasPlaying) {
				mPlayer.pause();
			}
		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if (fromUser) {
				mPlayer.seekTo(progress);
			}
		}

	};
}
